package com.aurora.source.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aurora.source.source.SourceApplication;
import com.aurora.source.util.LogUtils;
import com.aurora.source.util.SPUtils;
import com.aurora.source.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;

import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Base Fragment
 * <p>
 * Created by Lance
 * 2018/07/06
 */
public abstract class BaseFragment<T extends BasePresenter> extends Fragment implements IBaseView {

    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";

    public int pageNo = 0;// 当前页码
    public int pageSize = 20;// 默认每页十条,可不传

    public Map<String, String> params;// 请求数据Map

    protected View mContentView;

    public Activity activity;

    public SourceApplication application;

    public String userId;// 用户 Id

    private Unbinder mUnbinder;
    protected T basePresenter;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        try {
            LogUtils.d("BaseFragment onCreate: ");
            super.onCreate(savedInstanceState);
            if (savedInstanceState != null) {
                boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                if (isSupportHidden) {
                    ft.hide(this);
                } else {
                    ft.show(this);
                }
                ft.commitAllowingStateLoss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            LogUtils.d("BaseFragment onCreateView: ");
            setBaseView(inflater, bindLayout());
            mUnbinder = ButterKnife.bind(this, mContentView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mContentView;
    }

    @SuppressLint("ResourceType")
    protected void setBaseView(@NonNull LayoutInflater inflater, @LayoutRes int layoutId) {
        try {
            if (layoutId <= 0) return;
            mContentView = inflater.inflate(layoutId, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = getActivity();
        basePresenter = attach();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        try {
            LogUtils.d("BaseFragment onViewCreated: ");
            super.onViewCreated(view, savedInstanceState);
            Bundle bundle = getArguments();
            application = (SourceApplication) activity.getApplication();
            userId = String.valueOf(SPUtils.get(activity, SPUtils.USER_ID, ""));
            initData(bundle);
            initView(savedInstanceState, mContentView);
            doBusiness();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Activity 跳转
     * finish 是否删除当前Activity
     *
     * @author Lance
     * created at 2017/6/9
     */
    public void gotoActivity(Class<? extends Activity> clazz) {
        try {
            Intent intent = new Intent(activity, clazz);
            this.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Activity 跳转
     * finish 是否删除当前Activity
     *
     * @author Lance
     * created at 2018/02/24
     */
    public void gotoActivity(Class<? extends Activity> clazz, Bundle bundle) {
        try {
            Intent intent = new Intent(activity, clazz);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            this.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 吐司 资源文件 文本
    public void showToast(int resId) {
        try {
            ToastUtils.showSingletonShort(activity, resId);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    // 吐司 内容
    public void showToast(String stringRes) {
        try {
            ToastUtils.showSingletonShort(activity, stringRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {
        LogUtils.d("BaseFragment onDestroyView: ");
        if (mContentView != null) {
            ((ViewGroup) mContentView.getParent()).removeView(mContentView);
        }
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        LogUtils.d("BaseFragment onDestroy: ");
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        try {
            LogUtils.d("BaseFragment onSaveInstanceState: ");
            super.onSaveInstanceState(outState);
            outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T extends View> T findViewById(@IdRes int id) {
        if (mContentView == null) throw new NullPointerException("ContentView is null.");
        return mContentView.findViewById(id);
    }

    public abstract T attach();

    // 打开相册/拍照
    public void showPictureSelector(int MaxSelect,boolean isCrop) {
        try {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(MaxSelect)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                    .setOutputCameraPath(application.getFilesDir().getAbsolutePath())// 自定义拍照保存路径,可不填
                    .enableCrop(isCrop)// 是否裁剪 true or false
                    .withAspectRatio(1,1)// 裁剪是否可旋转图片 true or false
                    .rotateEnabled(true)// 裁剪是否可旋转图片 true or false
                    .isDragFrame(false)// 是否可拖动裁剪框(固定)
                    .previewImage(true)//是否可预览图片 true or false
                    .previewVideo(true)//是否可预览视频 true or false
                    .compress(true)// 是否压缩 true or false
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .compressSavePath(application.getFilesDir().getAbsolutePath())//压缩图片保存地址
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                    .openClickSound(true)// 是否开启点击声音 true or false
                    .cropCompressQuality(80)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 打开相册/拍照
    public void showVideoSelector(int MaxSelect) {
        try {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofVideo())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(MaxSelect)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                    .setOutputCameraPath(application.getFilesDir().getAbsolutePath())// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .compressSavePath(application.getFilesDir().getAbsolutePath())//压缩图片保存地址
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                    .openClickSound(true)// 是否开启点击声音 true or false
                    .cropCompressQuality(80)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(2000)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                    .forResult(PictureConfig.REQUEST_CAMERA);//结果回调onActivityResult code
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
